package com.example.unisys.controller;


import com.alibaba.fastjson.JSONObject;
import com.example.unisys.common.Response;
import com.example.unisys.common.STATUS;
import com.example.unisys.entity.Course;
import com.example.unisys.entity.CourseSale;
import com.example.unisys.entity.SubCourse;
import com.example.unisys.entity.Tag;
import com.example.unisys.service.CourseSaleService;
import com.example.unisys.service.CourseService;
import com.example.unisys.service.SubCourseService;
import com.example.unisys.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping(value = "/apis/v1", produces = "application/json; charset=utf-8")
public class SubAdminController {

    @Autowired
    SubCourseService subCourseService;

    @Autowired
    CourseService courseService;

    @Autowired
    CourseSaleService courseSaleService;

    @Autowired
    TagService tagService;

    /*
     * 分校管理员课程
     * */
    @RequestMapping(value = "/valid/courses", method = RequestMethod.POST)
    public Response validCourse(@RequestBody JSONObject jsonParam) {
        HashMap<String, Object> res = new HashMap<>();
        SubCourse subCourse = JSONObject.parseObject(jsonParam.toJSONString(), SubCourse.class);
        String course_id = subCourse.getCourse_id();
        Course course = courseService.getById(course_id);
        HashMap<String, Object> hs = new HashMap<>();
        hs.put("course_id", subCourse.getCourse_id());
        hs.put("main_school", subCourse.getMain_school());
        hs.put("sub_school", subCourse.getSub_school());
        List<CourseSale> cs = courseSaleService.getAllById(hs);
        if (cs.size() == 0) {
            CourseSale coursesale = CourseSale.builder().build();
            coursesale.setCourse_id(subCourse.getCourse_id());
//            coursesale.setCourse_name(subCourse.getCourse_name());
            coursesale.setMain_school(subCourse.getMain_school());
            coursesale.setSales(0);
            coursesale.setSub_school(subCourse.getSub_school());
            Tag tag = tagService.getActiveTag();
            coursesale.setTag(tag.getTag_name());
            courseSaleService.insertSelective(coursesale);
        }
        if (subCourseService.insert(subCourse) == 1)
            return Response.builder().status(STATUS.SUCCESS).build();
        return Response.builder().status(STATUS.BAD_REQUEST).build();
    }

    /*
     * 下架课程
     * */
    @RequestMapping(value = "/valid/courses/{course_id}", method = {RequestMethod.DELETE})
    public Response unshiftCourse(@PathVariable("course_id") String course_id) {
        HashMap<String, Object> res = new HashMap<>();
        if (subCourseService.delete(course_id) == 1)
            return Response.builder().status(STATUS.SUCCESS).build();
        return Response.builder().status(STATUS.BAD_REQUEST).build();

    }
}
